<?php
    #-------------------------------------------------------------#
	# This file is part of the Kumomado - Virtual Window Platform #
	# for PHP. (c) 2009 Tsai, Min Che <tirme0812@gmail.com>       #
	# Please visit http://www.kumomado.org/ for more information. #
	#                                                             #
	# This software is licensed under the GNU License v3. Please  #
	# view the LICENSE file for the full text of this license.    #
    #-------------------------------------------------------------#

	Kumomado::load('Database.KumomadoAbstractDatabase');
	
	/**
	 * @package libraries/database/mysql/
	 * @author Tsai, Min Che
	 * @version 1.0
	 */
	class MySQL extends KumomadoAbstractDatabase {
		/**
		 * @var resource
		 */
		protected $connect = false;
		/**
		 * @var array
		 */
		private $db_config = array();
		/**
		 * Construct
		 * @param string $db_name[optional]
		 * @param string $config_name[optional]
		 * @param string $prefix[optional]
		 */
		public function __construct($db_config, $prefix = 'kumomado') {
			$this->_setPrefix($prefix);
			$this->db_config = $db_config;
		}
		/**
		 * Connect to the database
		 * @return bool successful?
		 */
		public function connect() {
			/** Check the PHP Extensons has mysql.dll */
			if (!extension_loaded('mysql')) {
				throw new KumomadoDatabaseException('MySQL extension not loaded');
			}
			if (isset($this->db_config['pcconnect']) && $this->db_config['pcconnect']) {
				$this->connect = mysql_pconnect($this->db_config['db_host'], $this->db_config['db_user'], $this->db_config['db_pass']);
			} else {
				$this->connect = mysql_connect($this->db_config['db_host'], $this->db_config['db_user'], $this->db_config['db_pass']);
			}
			if (!$this->connect) {
				Kumomado::logger()->addQuery('', $this->error(), $this->errorNo());
				return false;
			}
			if ($this->db_config['db_name'] != '') {
				if (!mysql_select_db($this->db_config['db_name'], $this->connect)) {
					Kumomado::logger()->addQuery('', $this->error(), $this->errorNo());
					return false;
				}
			}
			if ($this->db_config['db_encode'] != '') {
				if (!mysql_query('SET CHARACTER SET '.$this->db_config['db_encode'])) {
					Kumomado::logger()->addQuery('', $this->error(), $this->errorNo());
					return false;
				}
			}
			$this->db_config = null;
			return true;
		}
		/**
		 * Perform a query on the database
		 * @return resource query result or FALSE if successful or TRUE if successful and no result
		 * @param string $sql a valid MySQL query
		 * @param int $limit number of records to return
		 * @param int $start offset of first record to return
		 */
		public function query($sql, $limit = 0, $start = 0) {
			if (!empty($limit)) {
				if (empty($start)) {
					$start = 0;
				}
				$sql = sprintf('%s LIMIT %s, %s', $sql, (int)$start, (int)$limit);
			}
			if ($result = mysql_query($sql, $this->connect)) {
				Kumomado::logger()->addQuery($sql);
				return $result;
			} else {
				Kumomado::logger()->addQuery($sql, $this->error(), $this->errorNo());
				return false;
			}			
		}
		/**
		 * Get the ID generated from the previous INSERT operation
		 * @return int
		 */
		public function getInsertId() {
			return mysql_insert_id($this->connect);
		}
		/**
		 * Returns escaped string text with single quotes around it to be safely stored in database
		 * @return string escaped string text with single quotes around
		 * @param string $str unescaped string text
		 */
		public function quoteString($str) {
			return sprintf('\'%s\'', str_replace('\\"', '"', addslashes($str)));
		}
		/**
		 * Return SQL Syntax string with back quotes
		 * @param string $syntax
		 * @return string
		 */
		public function quoteSyntax($syntax) {
			return sprintf('`%s`', $syntax);
		}
		/**
		 * Get a result row as an enumerated array
		 * @return array
		 * @param resource $result
		 */
		function fetchRow($result) {
			return @mysql_fetch_row($result);
		}
		/**
		 * Fetch a result row as an associative array
		 * @return array
		 */
		function fetchArray($result){
			return @mysql_fetch_assoc($result);
		}
		/**
		 * Fetch a result row as an associative array
		 * @return array
		 */
		function fetchBoth($result) {
			return @mysql_fetch_array($result, MYSQL_BOTH);
		}
		/**
		 * Get field name
		 * @return string
		 * @param resource $result query result
		 * @param int $offset field index
		 */
		function getFieldName($result, $offset) {
			return mysql_field_name($result, $offset);
		}
		/**
		 * Get field type
		 * @return string
		 * @param resource $result query result
		 * @param int $offset numerical field index
		 */
		function getFieldType($result, $offset) {
			return mysql_field_type($result, $offset);
		}
		/**
		 * Get number of rows in result
		 * @return int
		 * @param resource query result
		 */
		function getRowsNum($result) {
			return @mysql_num_rows($result);
		}
		/**
		 * Get number of affected rows
		 * @return int
		 */
		function getAffectedRows() {
			return mysql_affected_rows($this->connect);
		}
		/**
		 * will free all memory associated with the result identifier result.
		 * @return bool TRUE on success or FALSE on failure.
		 * @param resource query result
		 */
		function freeRecordSet($result) {
			return mysql_free_result($result);
		}
		/**
		 * Returns the text of the error message from previous MySQL operation
		 * @return bool Returns the error text from the last MySQL function, or '' (the empty string) if no error occurred.
		 */
		function error() {
			return @mysql_error();
		}
		/**
		 * Returns the numerical value of the error message from previous MySQL operation
		 * @return int Returns the error number from the last MySQL function, or 0 (zero) if no error occurred.
		 */
		function errorNo() {
			return @mysql_errno();
		}
		/**
		 * Close MySQL connection
		 */
		public function close() {
			mysql_close($this->connect);
		}
	}
?>